var location = require('location');
var iot = require('iot');

var loc = location.open();


var productKey = "productKey";
var deviceName = "deviceName";
var deviceSecret = "deviceSecret";

var device;

/**
 * location function
*/
var bts;
var nearbts;
function lbs_location()
{
    var mcc = loc.getAccessedLbsInfo().mcc;
    var mnc = loc.getAccessedLbsInfo().mnc;
    var cellid = loc.getAccessedLbsInfo().cellid;
    var lac = loc.getAccessedLbsInfo().lac;
    var signal = loc.getAccessedLbsInfo().signal;

    console.log('mcc ' + mcc + ' mnc ' + mnc + ' cellid ' + cellid + ' lac ' + lac + ' signal ' + signal);
    bts = mcc + ',' + mnc + ',' + lac + ',' + cellid + ',' + signal;
    nearbts = mcc + ',' + mnc + ',' + lac + ',' + cellid + ',' + signal;

    console.log('bts is ' + bts);
    console.log('neartbts ' + nearbts);
}

device = iot.device({
    productKey: productKey,
    deviceName: deviceName,
    deviceSecret: deviceSecret,
    region: 'cn-shanghai',
    success: function () {
        console.log('connect success');
        onConnect();
    },
    fail: function () {
        console.log('connect failed');
    }
});

function onConnect() {
    setInterval(function () {
        lbs_location();
        device.postEvent({
            id: 'LocationInfo',
            params: {
                cdma: '0',
                bts: bts,
                nearbts: nearbts
            },
            success: function () {
                console.log('postEvent success');

            },
            fail: function () {
                console.log('postEvent failed');
            }
        });
    }, 6000);
}

device.on('connect', function () {
    console.log('(re)connected');
});

/* 网络断开事件 */
device.on('disconnect', function () {
    console.log('disconnect ');
});

/* 关闭连接事件 */
device.on('close', function () {
    console.log('iot client just closed');
});

/* 发生错误事件 */
device.on('error', function (err) {
    console.log('error ' + err);
});

/* 云端设置属性事件 */
device.on('props', function (payload) {
    console.log('cloud req data is ', payload);
});

/* 云端下发服务事件 */
device.on('service', function (id, payload) {
    console.log('received cloud serviceid is ' + id);
    console.log('received cloud req_data is ' + payload);
});